package com.Alan.servlet.user;

import com.Alan.pojo.User;
import com.Alan.service.user.UserService;
import com.Alan.service.user.UserServiceImpl;
import com.Alan.util.Constants;
import com.Alan.util.UtilsAlan;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @CreateDate 2021/8/9 15:01
 */
public class LoginServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String name = req.getParameter("name");
        String password = req.getParameter("password");

        UserService userService = new UserServiceImpl();
        User user = userService.login(name);
        if (user != null){
            if (user.getUserPassword().equals(password)){
                req.getSession().setAttribute(Constants.USER_SESSION, user);
                req.getSession().setAttribute(Constants.NOWDATE, UtilsAlan.getNowDateStr());
                req.getSession().setAttribute(Constants.NOWWEEK, UtilsAlan.getNowWeek());
                resp.sendRedirect(req.getContextPath() + "/JSP/frame.jsp");
            }else {
                req.setAttribute("error", "密码错误");
                req.getRequestDispatcher(req.getContextPath() + "/login.jsp").forward(req, resp);
            }
        }else {
            req.setAttribute("error", "用户名错误");
            req.getRequestDispatcher(req.getContextPath() + "/login.jsp").forward(req, resp);
        }
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }
}
